<template>
  <div class="order-confirm">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container" v-loading="isLoading" element-loading-text="正在加载订单信息...">
    </div>
    
    <div v-else>
      <div class="header">
        <h1>确认订单</h1>
      </div>
      
      <!-- 如果没有商品数据，显示提示 -->
      <div v-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="购物车为空，请先选择商品">
          <el-button type="primary" @click="router.push('/')">去购物</el-button>
        </el-empty>
      </div>
      
      <el-card class="shipping-address-card">
        <div class="card-title">收货地址</div>
        <div class="address-info" v-if="hasCompleteAddress">
          <div class="address-name">{{ shippingAddress.receiverName }}</div>
          <div class="address-phone">{{ shippingAddress.receiverPhone }}</div>
          <div class="address-detail">{{ shippingAddress.province }}{{ shippingAddress.city }}{{ shippingAddress.district }}{{ shippingAddress.address }}</div>
          <el-button type="text" @click="editAddress">修改地址</el-button>
        </div>
        <div v-else class="address-form">
          <el-form :model="shippingAddress" label-width="80px">
            <el-form-item label="收货人">
              <el-input v-model="shippingAddress.receiverName" placeholder="请输入收货人姓名" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="shippingAddress.receiverPhone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="省份">
              <el-input v-model="shippingAddress.province" placeholder="请输入省份" />
            </el-form-item>
            <el-form-item label="城市">
              <el-input v-model="shippingAddress.city" placeholder="请输入城市" />
            </el-form-item>
            <el-form-item label="区县">
              <el-input v-model="shippingAddress.district" placeholder="请输入区县" />
            </el-form-item>
            <el-form-item label="详细地址">
              <el-input v-model="shippingAddress.address" placeholder="请输入详细地址" type="textarea" />
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      
      <el-card class="order-items-card">
        <div class="card-title">商品信息</div>
        <div class="order-items">
          <div 
            v-for="item in cartItems" 
            :key="item.id" 
            class="order-item"
            @click="goToProductDetail(item.id)"
          >
            <img :src="item.imageUrl" alt="商品图片" class="item-image">
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
              <div class="item-quantity">x{{ item.quantity }}</div>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card class="payment-method-card">
        <div class="card-title">支付方式</div>
        <div class="payment-methods">
          <el-radio-group v-model="paymentMethod">
            <el-radio :label="1">微信支付</el-radio>
            <el-radio :label="2">支付宝</el-radio>
            <el-radio :label="3">银行卡支付</el-radio>
            <el-radio :label="4">货到付款</el-radio>
          </el-radio-group>
        </div>
      </el-card>
      
      <el-card class="order-amount-card">
        <div class="card-title">金额信息</div>
        <div class="amount-info">
          <div class="amount-item">
            <span class="amount-label">商品总价：</span>
            <span class="amount-value">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="amount-item">
            <span class="amount-label">运费：</span>
            <span class="amount-value">¥{{ shippingFee.toFixed(2) }}</span>
          </div>
          <div class="amount-item total">
            <span class="amount-label">实付金额：</span>
            <span class="amount-value">¥{{ (totalAmount + shippingFee).toFixed(2) }}</span>
          </div>
        </div>
      </el-card>
      
      <div class="order-actions">
        <el-button type="primary" size="large" @click="submitOrder">
          提交订单
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { orderService } from '../services/orderService'
import { productService } from '../services/productService'
import { userService } from '../services/authService'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../store'
import { useCartStore } from '../store'
import api from '../utils/api'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 购物车商品数据
const cartItems = ref([])

// 页面加载状态
const isLoading = ref(false)

// 收货地址
const shippingAddress = ref({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: ''
})

// 支付方式（默认微信支付）
const paymentMethod = ref(1)

// 运费
const shippingFee = ref(0)

// 订单备注
const remark = ref('')

// 计算商品总价
const totalAmount = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

// 判断地址是否完整
const hasCompleteAddress = computed(() => {
  return shippingAddress.value.receiverName && 
         shippingAddress.value.receiverPhone && 
         shippingAddress.value.province && 
         shippingAddress.value.city && 
         shippingAddress.value.address
})

// 加载购物车数据
const loadCartItems = async () => {
  try {
    isLoading.value = true
    
    // 从localStorage获取购物车数据
    const checkoutCart = localStorage.getItem('checkoutCart')
    const buyNowProduct = localStorage.getItem('buyNowProduct')
    
    console.log('从localStorage获取购物车数据:', { checkoutCart, buyNowProduct })
    
    if (checkoutCart) {
      cartItems.value = JSON.parse(checkoutCart)
      console.log('解析后的购物车数据:', cartItems.value)
    } else if (buyNowProduct) {
      // 处理立即购买的情况
      const productInfo = JSON.parse(buyNowProduct)
      console.log('立即购买商品信息:', productInfo)
      
      try {
        // 从服务器获取商品详情，确保数据准确性
        const productDetail = await productService.getProductDetail(productInfo.productId)
        console.log('获取商品详情成功:', productDetail)
        
        // 检查库存是否充足
        if (productDetail.stock < productInfo.quantity) {
          ElMessage.error('商品库存不足，请减少购买数量')
          router.push('/cart')
          return
        }
        
        // 使用真实的商品数据创建订单项
        cartItems.value = [{
          id: productInfo.productId,
          quantity: productInfo.quantity,
          name: productInfo.productName || productDetail.name,
          price: productInfo.productPrice || productDetail.price,
          imageUrl: productInfo.productImage || productDetail.imageUrl || '/product.jpg'
        }]
        
        console.log('立即购买商品数据构建完成:', cartItems.value)
      } catch (productError) {
        console.error('获取商品详情失败:', productError)
        // 如果获取商品详情失败，使用localStorage中的数据
        cartItems.value = [{
          id: productInfo.productId,
          quantity: productInfo.quantity,
          name: productInfo.productName || '商品名称',
          price: productInfo.productPrice || 0,
          imageUrl: productInfo.productImage || '/product.jpg'
        }]
        ElMessage.warning('商品信息可能不是最新的，请以实际订单为准')
      }
    } else {
      console.warn('没有找到购物车数据')
      cartItems.value = []
    }
    
    // 如果购物车为空，显示提示但不跳转
    if (cartItems.value.length === 0) {
      console.warn('购物车为空')
      ElMessage.warning('购物车为空，请先选择商品')
    }
  } catch (error) {
    console.error('加载购物车数据失败:', error)
    ElMessage.error('加载购物车数据失败')
    // 不跳转，让用户看到错误信息
  } finally {
    isLoading.value = false
  }
}

// 修改地址
const editAddress = () => {
  // 清空当前地址，让用户重新填写
  shippingAddress.value = {
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    address: ''
  }
  ElMessage.info('请重新填写收货地址')
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 提交订单
const submitOrder = async () => {
  try {
    if (!userStore.isAuthenticated) {
      ElMessage.warning('请先登录')
      // 不自动跳转到登录页，而是让用户决定
      ElMessageBox.confirm('请先登录后再提交订单', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
      return
    }

    // 验证地址信息是否完整
    if (!hasCompleteAddress.value) {
      ElMessage.error('请填写完整的收货地址信息')
      return
    }
    
    // 确保使用当前用户的真实地址信息
    let finalReceiverName = shippingAddress.value.receiverName;
    let finalReceiverPhone = shippingAddress.value.receiverPhone;
    let finalReceiverAddress = `${shippingAddress.value.province}${shippingAddress.value.city}${shippingAddress.value.district}${shippingAddress.value.address}`;
    
    // 如果表单中的信息看起来是测试数据或空，尝试使用用户的真实信息
    if (userStore.userInfo?.id) {
      try {
        const userProfile = await userService.getUserProfile();
        if (userProfile) {
          console.log('验证收货地址信息，用户真实信息:', {
            username: userProfile.username,
            nickName: userProfile.nickName,
            phoneNumber: userProfile.phoneNumber,
            address: userProfile.address
          });
          
          // 如果表单中的收货人为空或是测试数据，使用用户的真实姓名
          if (!finalReceiverName || finalReceiverName === '张三' || finalReceiverName.trim() === '') {
            finalReceiverName = userProfile.nickName || userProfile.username || '未知用户';
            console.log('使用用户真实姓名:', finalReceiverName);
          }
          
          // 如果表单中的手机号为空或是测试数据，使用用户的真实手机号
          if (!finalReceiverPhone || finalReceiverPhone === '13800138000' || finalReceiverPhone.trim() === '') {
            finalReceiverPhone = userProfile.phoneNumber || '';
            console.log('使用用户真实手机号:', finalReceiverPhone);
          }
          
          // 如果表单中的地址为空或是测试数据，使用用户的真实地址
          if (!finalReceiverAddress || finalReceiverAddress.includes('测试地址') || finalReceiverAddress.trim() === '') {
            finalReceiverAddress = userProfile.address || '';
            console.log('使用用户真实地址:', finalReceiverAddress);
          }
        }
      } catch (error) {
        console.warn('获取用户真实信息失败，使用表单中的地址信息:', error);
      }
    }
    
    // 构建订单数据
    const orderData = {
      receiverName: finalReceiverName,
      receiverPhone: finalReceiverPhone,
      receiverAddress: finalReceiverAddress,
      remark: remark.value,
      items: cartItems.value.map(item => ({
        productId: item.id,
        quantity: item.quantity,
        price: item.price
      }))
    }
    
    console.log('提交订单数据:', orderData)
    
    // 调用创建订单接口
    const result = await orderService.createOrder(orderData)
    
    console.log('订单创建结果:', result)
    
    // 检查订单是否创建成功
    if (result && result.id) {
      ElMessage.success('订单创建成功')
      
      // 清空购物车
      localStorage.removeItem('checkoutCart')
      localStorage.removeItem('buyNowProduct')
      
      // 清空实际购物车
      await cartStore.clearCart()
      
      // 跳转到付款页面
      router.push(`/order/payment/${result.id}`)
    } else {
      ElMessage.error('订单创建失败')
    }
  } catch (error) {
    console.error('订单创建失败:', error)
    
    // 处理401错误 - 尝试刷新token
    if (error.statusCode === 401) {
      try {
        // 尝试使用refreshToken获取新的token
        const refreshResult = await api.post('/api/auth/refresh-token', null, {
          params: {
            refreshToken: userStore.refreshToken
          }
        })
        
        if (refreshResult && refreshResult.token) {
          // 更新用户store中的token
          userStore.updateAfterRefresh(refreshResult)
          
          // 重新提交订单
          ElMessage.info('正在重新提交订单...')
          setTimeout(() => {
            submitOrder()
          }, 1000)
          return
        }
      } catch (refreshError) {
        console.error('刷新token失败:', refreshError)
      }
      
      // 如果刷新token失败，提示用户重新登录
      ElMessage.error('登录已过期，请重新登录')
      ElMessageBox.confirm('登录已过期，是否重新登录？', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 保存当前订单数据，以便登录后恢复
        localStorage.setItem('pendingOrder', JSON.stringify({
          receiverName: shippingAddress.value.receiverName,
          receiverPhone: shippingAddress.value.receiverPhone,
          receiverAddress: `${shippingAddress.value.province}${shippingAddress.value.city}${shippingAddress.value.district}${shippingAddress.value.address}`,
          remark: remark.value,
          items: cartItems.value.map(item => ({
            productId: item.id,
            quantity: item.quantity,
            price: item.price
          }))
        }))
        
        router.push('/login')
      }).catch(() => {
        // 用户选择不登录，不做任何操作
      })
    } else {
      // 根据错误类型提供更友好的错误提示
      if (error.response) {
        // 服务器返回的错误
        switch (error.response.status) {
          case 400:
            ElMessage.error('订单数据不正确，请检查后重试')
            break
          case 403:
            ElMessage.error('无权限创建订单')
            break
          case 500:
            ElMessage.error('服务器错误，请稍后再试')
            break
          default:
            ElMessage.error(`订单创建失败: ${error.response.data?.message || '未知错误'}`)
        }
      } else if (error.request) {
        // 请求已发出但没有收到响应
        ElMessage.error('网络错误，请检查网络连接')
      } else {
        // 请求设置出错
        ElMessage.error(`订单创建失败: ${error.message}`)
      }
    }
  }
}

// 获取当前登录用户的地址信息
const loadUserAddress = async () => {
  try {
    if (!userStore.userInfo?.id) {
      console.warn('用户未登录，无法获取地址信息')
      return
    }
    
    console.log('获取用户地址信息，用户ID:', userStore.userInfo.id)
    const userProfile = await userService.getUserProfile()
    console.log('获取用户详细信息成功:', userProfile)
    
    // 如果用户有地址信息，使用真实数据
    if (userProfile && userProfile.address) {
      // 解析地址字符串，格式：省份城市区县详细地址
      const address = userProfile.address
      let province = '', city = '', district = '', detailAddress = ''
      
      // 简单的地址解析逻辑
      if (address.length >= 2) {
        province = address.substring(0, 2)
        if (address.length >= 4) {
          city = address.substring(2, 4)
          if (address.length >= 6) {
            district = address.substring(4, 6)
            detailAddress = address.substring(6)
          } else {
            detailAddress = address.substring(4)
          }
        } else {
          detailAddress = address.substring(2)
        }
      } else {
        detailAddress = address
      }
      
      shippingAddress.value = {
        receiverName: userProfile.nickName || userProfile.username || '',
        receiverPhone: userProfile.phoneNumber || '',
        province: province,
        city: city,
        district: district,
        address: detailAddress
      }
      
      console.log('使用用户真实地址信息:', shippingAddress.value)
    } else {
      console.log('用户没有地址信息，使用注册时的信息')
      // 使用注册时的基本信息
      shippingAddress.value = {
        receiverName: userProfile.nickName || userProfile.username || '',
        receiverPhone: userProfile.phoneNumber || '',
        province: '',
        city: '',
        district: '',
        address: userProfile.address || ''
      }
    }
  } catch (error) {
    console.error('获取用户地址信息失败:', error)
    // 如果获取失败，保持当前地址不变
  }
}

// 页面加载时初始化数据
onMounted(async () => {
  console.log('订单确认页面加载，开始初始化数据...')
  
  try {
    // 检查是否有待提交的订单数据
    const pendingOrderData = localStorage.getItem('pendingOrder')
    if (pendingOrderData) {
      try {
        const orderData = JSON.parse(pendingOrderData)
        
        // 恢复收货地址
        shippingAddress.value = {
          receiverName: orderData.receiverName || '',
          receiverPhone: orderData.receiverPhone || '',
          province: orderData.receiverAddress?.substring(0, 2) || '',
          city: orderData.receiverAddress?.substring(2, 4) || '',
          district: orderData.receiverAddress?.substring(4, 6) || '',
          address: orderData.receiverAddress?.substring(6) || ''
        }
        
        // 恢复备注
        remark.value = orderData.remark || ''
        
        // 清除待提交的订单数据
        localStorage.removeItem('pendingOrder')
        
        ElMessage.success('已恢复您的订单数据，请确认后提交')
      } catch (error) {
        console.error('恢复订单数据失败:', error)
        localStorage.removeItem('pendingOrder')
      }
    }
    
    // 检查是否有立即购买或购物车数据
    const buyNowProduct = localStorage.getItem('buyNowProduct')
    const checkoutCart = localStorage.getItem('checkoutCart')
    
    console.log('检查订单数据来源:', { buyNowProduct, checkoutCart })
    
    if (!buyNowProduct && !checkoutCart) {
      console.warn('没有找到订单数据，将跳转回首页')
      ElMessage.warning('请先选择商品再下单')
      router.push('/')
      return
    }
    
    // 加载购物车数据
    loadCartItems()
    
    // 如果没有恢复的收货地址，获取当前用户的真实地址信息
    if (!shippingAddress.value.receiverName && userStore.isAuthenticated) {
      await loadUserAddress()
    }
    
    // 设置运费（这里简单设置为0）
    shippingFee.value = 0
    
    console.log('订单确认页面初始化完成')
  } catch (error) {
    console.error('订单确认页面初始化失败:', error)
    ElMessage.error('页面初始化失败，请刷新页面重试')
  }
})
</script>

<style scoped>
.order-confirm {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  font-size: 28px;
}

.empty-cart {
  margin: 50px 0;
  text-align: center;
}

.shipping-address-card,
.order-items-card,
.payment-method-card,
.order-amount-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.address-info {
  padding: 20px;
}

.address-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.address-phone {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.address-detail {
  font-size: 14px;
  line-height: 1.6;
}

.order-items {
  padding: 20px;
}

.order-item {
  display: flex;
  gap: 15px;
  cursor: pointer;
  padding: 10px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
  margin-bottom: 10px;
}

.order-item:hover {
  background-color: #f5f5f5;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
}

.item-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  font-size: 16px;
  color: #ff4d4f;
  margin-bottom: 5px;
}

.item-quantity {
  font-size: 14px;
  color: #666;
}

.payment-methods {
  padding: 20px;
}

.amount-info {
  padding: 20px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.amount-item.total {
  font-size: 18px;
  font-weight: bold;
  border-bottom: none;
}

.amount-label {
  color: #666;
}

.amount-value {
  color: #333;
}

.amount-item.total .amount-value {
  color: #ff4d4f;
}

.order-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.address-form {
  padding: 20px 0;
}

.address-form .el-form-item {
  margin-bottom: 15px;
}

.address-form .el-input {
  width: 100%;
}
</style>